<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\BaseController;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;

class StandardProcess extends BaseController
{
    public function import()
    {
        // 获取项目id
        if (empty(input('project_id'))) {
            $this->error('请传入项目id');
        }

        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error('请上传文件！');
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error('文件上传失败');
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'zrr', $file['file']);

        $data = (new FileImport())->ExcelImport($file_path . $file_name, 0);

        $insert_array = [];
        $error_array = [];
        $i = 1;

        foreach ($data as $k => $v) {
            $i++;

            if ($k == 0) continue;
            if ($k == 1) continue;

            $status = $v[6] ?? null;
            if ($status == 0) {
                $status = 2;
            } else {
                $status = 1;
            }

            $insert_array[] = [
                'project_id' => input('project_id'),
                'type' => $v[5] ?? null,
                'number' => $v[2] ?? null,
                'name' => $v[3] ?? null,
                'status' => $status,
                'create_time' => date('Y-m-d H:i:s'),
            ];
        }

        if (!empty($error_array)) {
            $error_msg = implode('，', $error_array);
            $this->error('导入失败：' . $error_msg);
        }

        try {
            Db::table('t_standard_process')->insertALl($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('导入成功');
    }
}